/**
 * 分析任务列表页
 */
var analysisList = {
    table: null,

    // 初始化
    init: function() {
        console.log('初始化分析任务列表页...');
        
        this.loadStatistics();
        this.initTable();
        this.bindEvents();
    },

    // 加载统计信息
    loadStatistics: function() {
        axios.get('/analysis/tasks')
            .then(res => {
                const tasks = res.data || [];
                
                // 统计各状态数量
                const total = tasks.length;
                const completed = tasks.filter(t => t.analysisStatus === 'completed').length;
                const running = tasks.filter(t => t.analysisStatus === 'running').length;
                const failed = tasks.filter(t => t.analysisStatus === 'failed').length;
                
                // 更新统计卡片
                $('#totalAnalysis').text(total);
                $('#completedAnalysis').text(completed);
                $('#runningAnalysis').text(running);
                $('#failedAnalysis').text(failed);
            })
            .catch(err => {
                console.error('加载统计信息失败:', err);
            });
    },

    // 初始化DataTable
    initTable: function() {
        const self = this;
        
        this.table = $('#analysisTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: function(data, callback) {
                axios.get('/analysis/tasks')
                    .then(res => {
                        callback({ data: res.data || [] });
                    })
                    .catch(err => {
                        console.error('加载分析任务列表失败:', err);
                        callback({ data: [] });
                    });
            },
            columns: [
                { data: 'analysisId' },
                { 
                    data: 'collectTaskId',
                    render: function(data, type, row) {
                        return `任务${data} - ${row.collectTaskName || '未命名'}`;
                    }
                },
                {
                    data: 'createTime',
                    render: function(data) {
                        if (!data) return '-';
                        const date = new Date(data);
                        return date.toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                    }
                },
                {
                    data: 'analysisStatus',
                    render: function(data) {
                        if (data === 'completed') {
                            return '<span class="badge bg-success"><i class="fas fa-check-circle"></i> 已完成</span>';
                        } else if (data === 'running') {
                            return '<span class="badge bg-info"><i class="fas fa-spinner fa-spin"></i> 分析中</span>';
                        } else if (data === 'failed') {
                            return '<span class="badge bg-danger"><i class="fas fa-times-circle"></i> 失败</span>';
                        } else {
                            return '<span class="badge bg-secondary">' + data + '</span>';
                        }
                    }
                },
                { 
                    data: 'duration',
                    render: function(data) {
                        return data || '-';
                    }
                },
                { 
                    data: 'totalPlatforms',
                    render: function(data) {
                        return data || '-';
                    }
                },
                { 
                    data: 'totalQuestions',
                    render: function(data) {
                        return data || '-';
                    }
                },
                { 
                    data: 'totalProducts',
                    render: function(data) {
                        return data || '-';
                    }
                },
                {
                    data: 'ourProductRatio',
                    render: function(data) {
                        if (!data) return '-';
                        const ratio = parseFloat(data);
                        let badgeClass = 'bg-secondary';
                        if (ratio >= 50) {
                            badgeClass = 'bg-success';
                        } else if (ratio >= 30) {
                            badgeClass = 'bg-info';
                        } else if (ratio > 0) {
                            badgeClass = 'bg-warning';
                        }
                        return `<span class="badge ${badgeClass}">${ratio}%</span>`;
                    }
                },
                {
                    data: null,
                    orderable: false,
                    render: function(data, type, row) {
                        let buttons = '';
                        
                        if (row.analysisStatus === 'completed') {
                            buttons += `
                                <button class="btn btn-sm btn-primary view-report" 
                                        data-id="${row.analysisId}"
                                        title="查看报告">
                                    <i class="fas fa-eye"></i> 查看
                                </button>
                            `;
                        }
                        
                        buttons += `
                            <button class="btn btn-sm btn-danger delete-analysis" 
                                    data-id="${row.analysisId}"
                                    title="删除分析">
                                <i class="fas fa-trash"></i>
                            </button>
                        `;
                        
                        return buttons;
                    }
                }
            ],
            order: [[0, 'desc']],
            language: {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sSearch": "搜索:",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                }
            }
        });
    },

    // 绑定事件
    bindEvents: function() {
        const self = this;
        
        // 刷新按钮
        $('#refreshBtn').on('click', function() {
            self.refresh();
        });
        
        // 查看报告
        $('#analysisTable').on('click', '.view-report', function() {
            const analysisId = $(this).data('id');
            self.viewReport(analysisId);
        });
        
        // 删除分析
        $('#analysisTable').on('click', '.delete-analysis', function() {
            const analysisId = $(this).data('id');
            self.deleteAnalysis(analysisId);
        });
    },

    // 刷新列表
    refresh: function() {
        this.loadStatistics();
        if (this.table) {
            this.table.ajax.reload();
        }
        
        Swal.fire({
            icon: 'success',
            title: '刷新成功',
            timer: 1000,
            showConfirmButton: false
        });
    },

    // 查看报告
    viewReport: function(analysisId) {
        // 设置全局变量传递参数
        window.currentAnalysisId = analysisId;
        
        // 加载报告页面（SPA模式）
        if (typeof loadPage === 'function') {
            loadPage('/pages/analysis/report.html');
        } else {
            // 独立访问模式
            window.location.href = `/pages/analysis/report.html?analysisId=${analysisId}`;
        }
    },
    
    // 跳转到任务列表
    goToTaskList: function() {
        // 如果在SPA模式下（有parent的loadPage函数）
        if (window.parent && typeof window.parent.loadPage === 'function') {
            window.parent.loadPage('/pages/task/list.html');
        } else {
            // 独立访问模式
            window.location.href = '/pages/task/list.html';
        }
    },

    // 删除分析
    deleteAnalysis: function(analysisId) {
        Swal.fire({
            title: '确认删除？',
            text: '删除后将无法恢复，确定要删除这个分析任务吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '确定删除',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                // 显示加载中
                Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // 调用删除接口
                axios.delete(`/analysis/${analysisId}`)
                    .then(res => {
                        Swal.fire({
                            icon: 'success',
                            title: '删除成功！',
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            this.refresh();
                        });
                    })
                    .catch(err => {
                        console.error('删除分析失败:', err);
                        Swal.fire({
                            icon: 'error',
                            title: '删除失败',
                            text: err.message || '删除分析任务时发生错误'
                        });
                    });
            }
        });
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    analysisList.init();
});

